from common.libs.MemberService import MemberService
from web.models.user import OauthUserBind, User
from web.views.api import route_api
from flask import request, jsonify
from application import app, db
from datetime import datetime


@route_api.route("/user/check-reg", methods=["GET", "POST"])
def check_reg():
    """检查是否注册"""
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    print("check_reg req===================================>", req)

    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        resp['code'] = -1
        resp['msg'] = "需要code"
        return jsonify(resp)

    openid = MemberService.getWeChatOpenId(code)

    if openid is None:
        resp['code'] = -1
        resp['msg'] = "调用微信出错"
        return jsonify(resp)

    bind_info = OauthUserBind.query.filter_by(openid=openid).first()  # 查找绑定用户
    if not bind_info:
        resp['code'] = -1
        resp['msg'] = "未绑定"
        return jsonify(resp)

    user_info = User.query.filter_by(uid=bind_info.uid).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = "未查询到绑定信息"
        return jsonify(resp)

    token = "%s#%s" % (MemberService.geneAuthCode(user_info), user_info.uid)
    resp['data'] = {'token': token}
    return jsonify(resp)


@route_api.route("/user/login", methods=["GET", "POST"])
def login():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    app.logger.info(req)

    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        resp['code'] = -1
        resp['msg'] = "需要code"
        return jsonify(resp)

    openid = MemberService.getWeChatOpenId(code)
    if openid is None:
        resp['code'] = -1
        resp['msg'] = "操作错误"
        return jsonify(resp)

    nickname = req['nickName'] if 'nickName' in req else ''
    sex = req['gender'] if 'gender' in req else 0
    avatar = req['avatarUrl'] if 'avatarUrl' in req else ''

    # 判断是否已经测试过，注册了直接返回一些信息
    bind_info = OauthUserBind.query.filter_by(openid=openid).first()
    if not bind_info:  # 没有注册，则注册，写入数据库
        with db.auto_commit():
            model_member = User(nickname=nickname, sex=sex, avatar=avatar, salt=MemberService.geneSalt(),
                                created_time=datetime.now())
            db.session.add(model_member)

        with db.auto_commit():
            model_bind = OauthUserBind(uid=model_member.uid, openid=openid, created_time=datetime.now())
            db.session.add(model_bind)
        print("================微信用户信息写入数据库==================")

        bind_info = model_bind
    else:
        print("================微信用户已注册==================")

    user_info = User.query.filter_by(uid=bind_info.uid).first()
    token = "%s#%s" % (MemberService.geneAuthCode(user_info), user_info.uid)
    resp['data'] = {'token': token}
    return jsonify(resp)


@route_api.route("/user/info")
def get_info():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    uid = int(req['uid']) if 'uid' in req else -1
    if uid <= 0:
        resp['code'] = -1
        resp['msg'] = "该用户不存在"
        return jsonify(resp)

    user_info = User.query.filter_by(uid=uid).first()
    if user_info:
        user_data = {
            "nickname": user_info.nickname,
            "sex": user_info.sex,
            "avatar": user_info.avatar
        }
        resp['data']['user_info'] = user_data

    print("user_info resp======================>", resp)

    return jsonify(resp)


@route_api.route("/user/set")
def user_set():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    uid = int(req['uid']) if 'uid' in req else -1
    if uid <= 0:
        resp['code'] = -1
        resp['msg'] = "该用户不存在"
        return jsonify(resp)

    nickname = req['nickname'] if 'nickname' in req else ''
    if not nickname:
        resp['code'] = -1
        resp['msg'] = "用户昵称不能为空"
        return jsonify(resp)

    if len(nickname) > 20:
        resp['code'] = -1
        resp['msg'] = "用户昵称长度不能超过20"
        return jsonify(resp)

    sex = req['sex'] if 'sex' in req else -1
    if sex == 'null':
        resp['code'] = -1
        resp['msg'] = "性别为空"
        return jsonify(resp)
    sex = int(sex)

    with db.auto_commit():
        user = User.query.filter_by(uid=uid).first()
        if not user:
            resp['code'] = -1
            resp['msg'] = "未找到该用户"
            return jsonify(resp)
        user.nickname = nickname
        user.sex = sex
        db.session.add(user)
    return jsonify(resp)


@route_api.route("/user/search")
def user_search():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    user_id = int(req['user_id']) if "user_id" in req else -1

    if user_id <= 0:
        resp['code'] = -1
        resp['msg'] = '操作错误'
        return jsonify(resp)

    user = User.query.filter_by(uid=user_id).first()
    if not user:
        resp['data']['user_info'] = {}
        return jsonify(resp)

    user_info = {
        'name': user.nickname,
        'avatar': user.avatar
    }
    resp['data']['user_info'] = user_info

    return jsonify(resp)
